#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long LL;
typedef double db;
inline int read()
{
	int x=0,f=1;
	char ch=getchar();
	while(ch<'0'||ch>'9') { if(ch=='-')f=-1; ch=getchar(); }
	while(ch>='0'&&ch<='9') { x=(x<<1)+(x<<3)+ch-'0'; ch=getchar(); }
	return x*f;
}
const int MAXN=3e4+10;
int n,m,sqr,head[MAXN*200],cnt,tot,S,T,dis[MAXN*200],pos[200][MAXN];
bool vis[MAXN*200];
struct edge
{
	int v,next,val;
}e[MAXN*500];
void addedge(int x,int y,int z)
{
	e[++cnt]=(edge){y,head[x],z};
	head[x]=cnt;
	return;
}
void SPFA()
{
	memset(dis,INF,sizeof(dis));
	dis[S]=0;
	queue<int>q;
	q.push(S);
	while(!q.empty())
	{
		int u=q.front();q.pop();vis[u]=false;
		for(int i=head[u];i;i=e[i].next)
		{
			int v=e[i].v;
			if(dis[v]>dis[u]+e[i].val)
			{
				dis[v]=dis[u]+e[i].val;
				if(!vis[v])
				{
					vis[v]=true;
					q.push(v);
				}
			}
		}
	}
	return;
}
int main()
{
#ifndef ONLINE_JUDGE
	freopen("in.in","r",stdin);
	freopen("out.out","w",stdout);
#endif
	n=read();m=read();
	sqr=min(int(sqrt(n)),100);
	tot=n;
	for(int i=1;i<=sqr;++i)
		for(int j=1;j<=i;++j)
			for(int k=j;k<=n;k+=i)
			{
				pos[i][k]=++tot;
				addedge(tot,k,0);
				if(k!=j)
				{
					addedge(tot,tot-1,1);
					addedge(tot-1,tot,1);
				}
			}
	for(int i=1;i<=m;++i)
	{
		int B=read()+1,P=read();
		if(i==1)S=B;
		else if(i==2)T=B;
		if(P<=sqr)
			addedge(B,pos[P][B],0);
		else
		{
			for(int j=B-P;j>0;j-=P)
				addedge(B,j,(B-j)/P);
			for(int j=B+P;j<=n;j+=P)
				addedge(B,j,(j-B)/P);
		}
	}
	SPFA();
	if(dis[T]==INF)puts("-1");
	else printf("%d\n",dis[T]);
	return 0;
}
